<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 床位号 -->
      <el-form-item label="床位号" prop="bedNo">
        <el-input
          v-model="queryParams.bedNo"
          placeholder="请输入床位号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['yucunkuan:yckchongzhi:add']"
          >充值</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="yckchongzhiList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="老人姓名" align="center" width="150">
        <template #default="scope">
          {{ scope.row.elderlyName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="床位号" align="center" width="200">
        <template #default="scope">
          {{ scope.row.bedNo || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="充值金额" align="center" prop="rechargeAmount" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" />
      <el-table-column
        label="充值凭证图片"
        align="center"
        prop="rechargeVoucher"
        width="100"
      >
        <template #default="scope">
          <image-preview
            :src="scope.row.rechargeVoucher"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作人" align="center" width="200">
        <template #default="">
          {{ userStore.nickName || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预存款充值对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        ref="yckchongzhiRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 隐藏的老人ID字段（用于接口提交） -->
        <el-form-item prop="elderlyId" hidden>
          <el-input v-model="form.elderlyId" hidden />
        </el-form-item>

        <el-form-item label="老人姓名" prop="elderlyName" required>
          <el-select
            v-model="form.elderlyName"
            placeholder="请选择老人姓名"
            clearable
            @change="handleElderlyChange"
            filterable
          >
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="
                elderly.bedNo
                  ? `${elderly.name} - ${elderly.bedNo}床`
                  : elderly.name
              "
              :value="elderly.name"
              :data-id="elderly.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值方式" prop="paymentMethod" required>
          <el-select
            v-model="form.paymentMethod"
            placeholder="请选择充值方式"
            clearable
          >
            <el-option
              v-for="method in paymentMethodList"
              :key="method.id"
              :label="method.name"
              :value="method.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargeAmount" required>
          <el-input
            v-model.number="form.rechargeAmount"
            placeholder="请输入充值金额"
          />
        </el-form-item>
        <el-form-item label="充值凭证" prop="rechargeVoucher" required>
          <image-upload v-model="form.rechargeVoucher" />
        </el-form-item>
        <el-form-item label="充值备注" prop="remark" required>
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入充值备注"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Yckchongzhi">
// 引入充值相关接口（原有）
import {
  listYckchongzhi,
  getYckchongzhi,
  delYckchongzhi,
  addYckchongzhi,
  updateYckchongzhi,
} from "@/api/yucunkuan/yckchongzhi";
// 新增：引入获取所有老人的接口（请替换为你项目中实际的老人列表接口）
import { listElderly } from "@/api/system/elderly";
import {
  getBalancefind,
  updateBalancefind,
  listBalancefind,
  getBalanceByElderlyId,
} from "@/api/balance/balancefind";
import { getCurrentInstance, ref, reactive, toRefs } from "vue";

import { useRouter } from "vue-router";

import useUserStore from "@/store/modules/user";
// 2. 获取用户存储实例
const userStore = useUserStore();
// 3. 在脚本中打印用户信息
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");

// 支付方式列表（原有）
const paymentMethodList = ref([
  { id: 1, name: "现金" },
  { id: 2, name: "微信" },
  { id: 3, name: "支付宝" },
]);

// 老人列表（修改为：从专门的老人接口获取全部老人）
const elderlyList = ref([]);

// 页面数据（原有）
const yckchongzhiList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("上传充值凭证");

// 表单数据（原有）
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderlyId: null,
    isDeleted: null,
  },
  rules: {
    elderlyId: [{ required: true, message: "请选择老人", trigger: "change" }],
    elderlyName: [
      { required: true, message: "请选择老人姓名", trigger: "change" },
    ],
    paymentMethod: [
      { required: true, message: "请选择充值方式", trigger: "change" },
    ],
    rechargeAmount: [
      { required: true, message: "请输入充值金额", trigger: "blur" },
      {
        type: "number",
        min: 0.01,
        message: "充值金额不能小于0.01",
        trigger: "blur",
      },
    ],
    rechargeVoucher: [
      { required: true, message: "请上传充值凭证", trigger: "change" },
    ],
    remark: [{ required: true, message: "请输入充值备注", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预存款充值列表（原有，移除提取老人的逻辑） */
function getList() {
  loading.value = true;
  listYckchongzhi(queryParams.value).then((response) => {
    yckchongzhiList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 新增：查询所有老人（从专门的老人接口获取） */
function getAllElderly() {
  // 调用老人列表接口（参数根据实际接口调整，这里查询全部老人）
  listElderly({ pageNum: 1, pageSize: 1000, isDeleted: 0 }) // 假设isDeleted=0表示未删除的老人
    .then((response) => {
      const rawElderlyList = response.rows || [];
      
      // 2. 基于老人ID去重（ID唯一，确保每个老人只出现一次）
      const uniqueElderlyMap = new Map();
      rawElderlyList.forEach(elderly => {
        // 以ID为key，若已存在则不重复添加
        if (!uniqueElderlyMap.has(elderly.id)) {
          uniqueElderlyMap.set(elderly.id, elderly);
        }
      });
      
      // 3. 将去重后的Map转换为数组，适配下拉框
      elderlyList.value = Array.from(uniqueElderlyMap.values()).map((elderly) => ({
        id: elderly.id,
        name: elderly.name,
        bedNo: elderly.bedNo,
      }));
    })
    .catch((error) => {
      console.error("获取老人列表失败：", error);
      proxy.$modal.msgError("获取老人信息失败，请重试");
    });
}

// 取消按钮（原有）
function cancel() {
  open.value = false;
  reset();
}

// 表单重置（原有）
function reset() {
  form.value = {
    id: null,
    rechargeNo: null,
    elderlyId: null,
    elderlyName: null,
    rechargeAmount: null,
    paymentMethod: null,
    rechargeVoucher: null,
    remark: null,
    operator: null,
    createTime: null,
    updateTime: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("yckchongzhiRef");
}

/** 搜索按钮操作（原有） */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作（原有） */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据（原有）
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作（原有） */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "上传充值凭证";
}

/** 选择老人时同步ID（原有，逻辑不变） */
function handleElderlyChange(selectedName) {
  const selectedElderly = elderlyList.value.find(
    (item) => item.name === selectedName
  );
  form.value.elderlyId = selectedElderly ? selectedElderly.id : null;
}

/** 提交按钮（原有） */
function submitForm() {
  proxy.$refs["yckchongzhiRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateYckchongzhi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 保存充值记录
        addYckchongzhi(form.value).then((response) => {
          


          // 充值成功后，更新对应老人的预交款余额
          if (form.value.elderlyId) {
            // 正确的调用方式：使用listBalancefind并传入查询参数
            getBalanceByElderlyId(form.value.elderlyId)
              .then((balanceResponse) => {
                // 检查是否有余额记录
                const balanceData = balanceResponse.data;
                if (!balanceData) {
                  // 如果没有余额记录，创建新记录
                  const newBalanceData = {
                    elderlyId: form.value.elderlyId,
                    elderlyName: form.value.elderlyName,
                    prepaymentBalance: form.value.rechargeAmount,
                    depositBalance: 0,
                  };
                  addBalancefind(newBalanceData)
                    .then(() => {
                      console.log("新增余额记录成功");
                    })
                    .catch((err) => {
                      console.error("新增余额记录失败：", err);
                      proxy.$modal.msgError("更新余额失败，请联系管理员");
                    });
                } else {
                  // 如果有余额记录，更新现有记录
                  const currentBalance = parseFloat(
                    balanceData.prepaymentBalance || 0
                  );
                  const rechargeAmount = parseFloat(
                    form.value.rechargeAmount || 0
                  );
                  const newBalance = currentBalance + rechargeAmount;

                  balanceData.prepaymentBalance = newBalance;
                  updateBalancefind(balanceData)
                    .then(() => {
                      console.log("更新余额成功");
                    })
                    .catch((err) => {
                      console.error("更新余额失败：", err);
                      proxy.$modal.msgError("更新余额失败，请联系管理员");
                    });
                }
              })
              .catch((err) => {
                console.error("查询余额失败：", err);
                proxy.$modal.msgError("查询余额失败，请联系管理员");
              });
          }

          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作（原有） */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除预存款充值编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delYckchongzhi(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作（原有） */
function handleExport() {
  proxy.download(
    "yucunkuan/yckchongzhi/export",
    {
      ...queryParams.value,
    },
    `yckchongzhi_${new Date().getTime()}.xlsx`
  );
}

// 初始化加载：同时加载充值列表和所有老人（修改点）
function init() {
  getList(); // 加载充值记录列表
  getAllElderly(); // 加载所有老人（用于下拉框）
}
init();
</script>
